#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import time, sys, datetime, logging
import pandas as pd

import db_utils as util

from app.models.T_DWD_FACT_ZZSC_LZZB_J001 import FeatureInfo, Summary, STSEntry, ExitPdoDataEntry, FactDetail, Range
from app.models.SideCut import TMMSIK108
from app.LoggableObject import LoggableObject


class GapJob(LoggableObject):
    """

    """
    config = None

    def __init__(self, p_config=None, ):
        super(GapJob, self).__init__()
        self.config = p_config
        pass

    def execute(self):
        self.logger.info('GapJob.execute')
        start = datetime.datetime.now()

        self.__do_execute()

        elapsed = float((datetime.datetime.now() - start).seconds)
        self.logger.info("Time Used 4 All ----->>>> %f seconds" % (elapsed))
        pass

    def __do_execute(self):
        """
        """

        db_conn_mpp = util.getConnectionDb2(self.config.DB_HOST_MPP_DB2_BGBDPROD,
                                            self.config.DB_PORT_MPP_DB2_BGBDPROD,
                                            self.config.DB_DBNAME_MPP_DB2_BGBDPROD,
                                            self.config.DB_USER_MPP_DB2_BGBDPROD,
                                            self.config.DB_PASSWORD_MPP_DB2_BGBDPROD)
        self.logger.info('connect db_conn_mpp success?????????????????')

        now = datetime.datetime.now()
        day = datetime.datetime(year=now.year, month=11, day=7, hour=3, minute=0).strftime('%Y%m%d%H%M%S')

        # FIXME hard code 1st
        day = '20201107'
        month = '202011'

        MAX_TIME1, MAX_TIME2 = self.__query_max_end_time(p_db_conn=db_conn_mpp)

        # close
        util.closeConnection(db_conn_mpp)

    def __query_max_end_time(self, p_db_conn=None):
        """

        :param p_db_conn:
        :return:
        """
        sql = "select MAX(END_TIME) as MAX_TIME1 from BGROSIDS.T_DWD_FACT_ZZSC_TRIM_PRED"
        try:
            df = util.query(conn=p_db_conn, sql=sql)
        except Exception as e:
            self.logger.error(str(e))
        # 起始时间
        MAX_TIME1 = None
        for index, row in df.iterrows():
            self.logger.info(row)
            MAX_TIME1 = row['MAX_TIME1']
        # 结束时间写死成昨天晚上8点(20: 00)
        yesterday = datetime.date.today() - datetime.timedelta(days=1)
        MAX_TIME2 = datetime.datetime(year=yesterday.year, month=yesterday.month, day=yesterday.day, hour=20).strftime(
            '%Y%m%d%H%M%S')
        return MAX_TIME1, MAX_TIME2

    def __cal_side_cut_len(self, db_conn_mpp=None, MAX_TIME1=None, MAX_TIME2=None):
        """
        连接DB2数据库   MPP
        Schema   MMSI
        TMMSIK108  每个钢卷预判量原始表

        读取excel标黄的字段
        得到预判切边量(需要经过参考excel的各个计算公式去计算才能得到)
        """
        sql = "select " \
              "* " \
              "from " \
              "MMSI.TMMSIK108 " \
              "where 1=1 " \
              "and prod_end_time>='%s' " \
              "and prod_end_time<'%s'" % (MAX_TIME1, MAX_TIME2)
        try:
            df = util.query(conn=db_conn_mpp, sql=sql)
        except Exception as e:
            self.logger.error(str(e))

        # 切边总长度
        mat_len_total = 0
        # 预判切变量
        side_cut_len_total = 0

        cut_datas = list()
        for index, row in df.iterrows():
            if index == 0:
                continue
            item = TMMSIK108(p_dic=row)

            tmp_cut_data = dict()

            tmp_ds_side_cut_len = row.get('ds_side_cut_len%d' % (index + 1))
            tmp_ws_side_cut_len = row.get('ws_side_cut_len%d' % (index + 1))
            tmp_prev_mat_len = row.get('mat_len_%d' % (index))
            tmp_mat_len = row.get('mat_len_%d' % (index + 1))

            if tmp_ds_side_cut_len == tmp_ws_side_cut_len == 0 or tmp_ds_side_cut_len == tmp_ws_side_cut_len == 10:
                # 没发生切边
                # 切边长度2 = 0
                # 切边量2 = 0
                tmp_cut_data['mat_len'] = 0
                tmp_cut_data['side_cut_len'] = 0
            else:
                # 发生了切边
                # 切边长度2 = LEN2 - LEN1
                # 切边量2 = DS2 + WS2
                tmp_cut_data['mat_len'] = tmp_prev_mat_len - tmp_mat_len
                tmp_cut_data['side_cut_len'] = tmp_ds_side_cut_len + tmp_ws_side_cut_len
            cut_datas.append(tmp_cut_data)

        # 切边总长度 = 切边长度2。。。+切边长度8
        # 预判切变量 = (切变量2 * 切边长度2 +。。。切变量8 * 切边长度8) / 切边总长度
        for tmp_cut_data in cut_datas:
            mat_len_total += tmp_cut_data['mat_len']
            side_cut_len_total += tmp_cut_data['side_cut_len'] * tmp_cut_data['mat_len']
        side_cut_len_total = side_cut_len_total / mat_len_total

        return mat_len_total, side_cut_len_total

    def __abc(self, p_item: TMMSIK108 = None):
        # A -- 钢卷号
        # B -- 长度
        # C -- 实测宽度
        # D -- FCL分卷长度
        # E -- 宽度
        # F -- DS切边量
        # G -- WS切边量
        # H -- 多切原因
        # I -- 多切宽度
        # J -- 切边长度
        # K -- 切边量
        # L -- 多切原因
        # M -- 多切宽度

        J3 = D3 - D2
        J4 = D4 - D3
        J5 = D5 - D4
        J6 = D6 - D5

        K3 = F3 + G3
        K4 = F4 + G4
        K5 = F5 + G5
        K6 = F6 + G6

        D16 = SUM(J3:J6)


        ds_side_cut_len = SUM(J3 * K3, J4 * K4, J5 * K5, J6 * K6) / D16

        pass

        # DS切边量	WS切边量
